package top.bigchen.camera;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v4.os.EnvironmentCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

    private final String TAG = getClass().getSimpleName();
    private Button mQlztButton,mKylhButton,mQtButton,mQdButton,mTmButton,mGglButton,mSbButton,mXbButton,mResetButton;
    private EditText mProjectNameEdit,mKmEdit,mBzEdit;
    private static final String PERMISSION_WRITE_STORAGE = Manifest.permission.WRITE_EXTERNAL_STORAGE;
    private static final int REQUEST_PERMISSION_CODE = 267;
    private  String mProjectName;
    private  String mKM="";
    private String mType="";
    private  String mBZ="";
    // 拍照的requestCode
    private static final int CAMERA_REQUEST_CODE = 0x00000010;
    // 申请相机权限的requestCode
    private static final int PERMISSION_CAMERA_REQUEST_CODE = 0x00000012;
    /**
     * 用于保存拍照图片的uri
     */
    private Uri mCameraUri;

    /**
     * 用于保存图片的文件路径，Android 10以下使用图片路径访问图片
     */
    private String mCameraImagePath;
    /**
     *  是否是Android 10以上手机
     */
    private boolean isAndroidQ = Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        /*申请读取存储的权限*/
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(PERMISSION_WRITE_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{PERMISSION_WRITE_STORAGE}, REQUEST_PERMISSION_CODE);
            }
        }
        mQlztButton = (Button) findViewById(R.id.qlzt_btn);
        mKylhButton = (Button) findViewById(R.id.kylh_btn);
        mQtButton = (Button) findViewById(R.id.qt_btn);
        mQdButton = (Button) findViewById(R.id.qd_btn);
        mTmButton = (Button) findViewById(R.id.tm_btn);
        mGglButton = (Button) findViewById(R.id.ggl_btn);
        mSbButton = (Button) findViewById(R.id.sb_btn);
        mXbButton = (Button) findViewById(R.id.xb_btn);
        mResetButton=(Button)findViewById(R.id.reset);
        mProjectNameEdit =(EditText)findViewById(R.id.projectname);
        mKmEdit =(EditText)findViewById(R.id.km);
        mBzEdit=(EditText)findViewById(R.id.bz);
        mQlztButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mProjectName=mProjectNameEdit.getText().toString();
                mKM=mKmEdit.getText().toString();
                if (TextUtils.isEmpty(mProjectName)||TextUtils.isEmpty(mKM)){
                    Toast.makeText(MainActivity.this,"请填写项目及桩号",Toast.LENGTH_LONG).show();
                    return;
                }
                mType="桥梁总体";
                checkPermissionAndCamera();
//              takePhoto(mProjectName,mKM,"桥梁总体");
            }
        });
        mKylhButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mProjectName=mProjectNameEdit.getText().toString();
                mKM=mKmEdit.getText().toString();
                if (TextUtils.isEmpty(mProjectName)||TextUtils.isEmpty(mKM)){
                    Toast.makeText(MainActivity.this,"请填写项目及桩号",Toast.LENGTH_LONG).show();
                    return;
                }
                //takePhoto(mProjectName,mKM,"跨越路河");
            }
        });
        mQtButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mProjectName=mProjectNameEdit.getText().toString();
                mKM=mKmEdit.getText().toString();
                if (TextUtils.isEmpty(mProjectName)||TextUtils.isEmpty(mKM)){
                    Toast.makeText(MainActivity.this,"请填写项目及桩号",Toast.LENGTH_LONG).show();
                    return;
                }
                //takePhoto(mProjectName,mKM,"桥台");
            }
        });
        mQdButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mProjectName=mProjectNameEdit.getText().toString();
                mKM=mKmEdit.getText().toString();
                if (TextUtils.isEmpty(mProjectName)||TextUtils.isEmpty(mKM)){
                    Toast.makeText(MainActivity.this,"请填写项目及桩号",Toast.LENGTH_LONG).show();
                    return;
                }
                //takePhoto(mProjectName,mKM,"桥墩");
            }
        });
        mTmButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mProjectName=mProjectNameEdit.getText().toString();
                mKM=mKmEdit.getText().toString();
                if (TextUtils.isEmpty(mProjectName)||TextUtils.isEmpty(mKM)){
                    Toast.makeText(MainActivity.this,"请填写项目及桩号",Toast.LENGTH_LONG).show();
                    return;
                }
               // takePhoto(mProjectName,mKM,"台帽");
            }
        });
        mGglButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mProjectName=mProjectNameEdit.getText().toString();
                mKM=mKmEdit.getText().toString();
                if (TextUtils.isEmpty(mProjectName)||TextUtils.isEmpty(mKM)){
                    Toast.makeText(MainActivity.this,"请填写项目及桩号",Toast.LENGTH_LONG).show();
                    return;
                }
                //takePhoto(mProjectName,mKM,"墩盖梁");
            }
        });
        mSbButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mProjectName=mProjectNameEdit.getText().toString();
                mKM=mKmEdit.getText().toString();
                if (TextUtils.isEmpty(mProjectName)||TextUtils.isEmpty(mKM)){
                    Toast.makeText(MainActivity.this,"请填写项目及桩号",Toast.LENGTH_LONG).show();
                    return;
                }
                //takePhoto(mProjectName,mKM,"上部");
            }
        });
        mXbButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mProjectName=mProjectNameEdit.getText().toString();
                mKM=mKmEdit.getText().toString();
                if (TextUtils.isEmpty(mProjectName)||TextUtils.isEmpty(mKM)){
                    Toast.makeText(MainActivity.this,"请填写项目及桩号",Toast.LENGTH_LONG).show();
                    return;
                }
                //takePhoto(mProjectName,mKM,"细部");
            }
        });
        mResetButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mProjectNameEdit.setText("");
                mKmEdit.setText("");
                mBzEdit.setText("");
            }
        });
    }
    /**
     * 检查权限并拍照。
     * 调用相机前先检查权限。
     */
    private void checkPermissionAndCamera() {
        int hasCameraPermission = ContextCompat.checkSelfPermission(getApplication(),
                Manifest.permission.CAMERA);
        if (hasCameraPermission == PackageManager.PERMISSION_GRANTED) {
            //有权限，调起相机拍照。
            openCamera(mProjectName,mKM,mType);
        } else {
            //没有权限，申请权限。
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CAMERA},
                    PERMISSION_CAMERA_REQUEST_CODE);
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CAMERA_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                if (isAndroidQ) {
                    // Android 10 使用图片uri加载
                } else {
                    // 使用图片路径加载
                }
            } else {
                Toast.makeText(this,"取消",Toast.LENGTH_LONG).show();
            }
        }
    }

    /**
     * 处理权限申请的回调。
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == PERMISSION_CAMERA_REQUEST_CODE) {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //允许权限，有调起相机拍照。
                openCamera(mProjectName,mKM,mType);
            } else {
                //拒绝权限，弹出提示框。
                Toast.makeText(this,"拍照权限被拒绝",Toast.LENGTH_LONG).show();
            }
        }
    }
    /**
     * 调起相机拍照
     */
    private void openCamera(String mProjectName,String mKM,String mType) {
        Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 判断是否有相机
        if (captureIntent.resolveActivity(getPackageManager()) != null) {
            File photoFile = null;
            Uri photoUri = null;

            if (isAndroidQ) {
                // 适配android 10
                photoUri = createImageUri( mProjectName,  mKM,  mType);
            } else {
                try {
                    photoFile = createImageFile(  mProjectName,  mKM,  mType);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (photoFile != null) {
                    mCameraImagePath = photoFile.getAbsolutePath();
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        //适配Android 7.0文件权限，通过FileProvider创建一个content类型的Uri
                        photoUri = FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", photoFile);
                    } else {
                        photoUri = Uri.fromFile(photoFile);
                    }
                }
            }

            mCameraUri = photoUri;
            if (photoUri != null) {
                captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                captureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                startActivityForResult(captureIntent, CAMERA_REQUEST_CODE);
            }
        }
    }
    /**
     * 创建图片地址uri,用于保存拍照后的照片 Android 10以后使用这种方法
     *
     * @return 图片的uri
     */
    private Uri createImageUri(String mProjectName,String mKM,String mType) {
        Uri imageFilePath = null;
        String status = Environment.getExternalStorageState();
        SimpleDateFormat timeFormatter = new SimpleDateFormat(
                "yyyyMMdd_HHmmss", Locale.CHINA);
        long time = System.currentTimeMillis();
        String imageName = timeFormatter.format(new Date(time));
        String imageFileName = mProjectName+"-" +mKM+"-"+mType+"-"+ imageName+".jpg";
        // ContentValues是我们希望这条记录被创建时包含的数据信息
        ContentValues values = new ContentValues(3);
        values.put(MediaStore.Images.Media.DISPLAY_NAME, imageFileName);
        values.put(MediaStore.Images.Media.DATE_TAKEN, time);
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg");
        if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡,优先使用SD卡存储,当没有SD卡时使用手机存储
            imageFilePath = getContentResolver().insert(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        } else {
            imageFilePath = getContentResolver().insert(
                    MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
        }
        Log.i("", "生成的照片输出路径：" + imageFilePath.toString());
        return imageFilePath;
//        String status = Environment.getExternalStorageState();
        // 判断是否有SD卡,优先使用SD卡存储,当没有SD卡时使用手机存储
//        if (status.equals(Environment.MEDIA_MOUNTED)) {
//            return getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
//        } else {
//            return getContentResolver().insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, new ContentValues());
//        }
    }

    /**
     * 创建保存图片的文件
     * @return
     * @throws IOException
     */
    private File createImageFile(String mProjectName,String mKM,String mType) throws IOException {
        String imageName = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        String imageFileName = mProjectName+"-" +mKM+"-"+mType+"-"+ imageName;
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        if (!storageDir.exists()) {
            storageDir.mkdir();
        }
        File tempFile = new File(storageDir, imageFileName);
        if (!Environment.MEDIA_MOUNTED.equals(EnvironmentCompat.getStorageState(tempFile))) {
            return null;
        }
        return tempFile;
    }



}
